<template>
	<view>
		<view class="example">
			<uni-forms ref="valiForm" :rules="rules" :modelValue="valiFormData">
				<uni-forms-item label="用车部门" required name="userDepartment">
					<uni-data-select v-model="valiFormData.userDepartment"
						:localdata="departmentRange"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="姓名" required name="userName">
					<uni-easyinput v-model="valiFormData.userName" placeholder="请输入姓名" />
				</uni-forms-item>
				<uni-forms-item label="工号" required name="userId">
					<uni-easyinput v-model="valiFormData.userId" placeholder="请输入工号" />
				</uni-forms-item>
				<uni-forms-item label="申请人电话" required name="userPhone">
					<uni-easyinput v-model="valiFormData.userPhone" placeholder="请输入电话" />
				</uni-forms-item>
				<uni-forms-item label="车型" required name="autoType">
					<uni-data-select v-model="valiFormData.autoType" :localdata="autoTypeRange"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="成员数" required name="passengerNum">
					<uni-easyinput v-model="valiFormData.passengerNum" placeholder="请输入成员数" />
				</uni-forms-item>
				<uni-forms-item label="取车时间" required name="autoStartTime">
					<uni-datetime-picker type="datetime" return-type="string" v-model="valiFormData.autoStartTime" />
				</uni-forms-item>
				<uni-forms-item label="截止时间" required name="autoArriveTime">
					<uni-datetime-picker type="datetime" return-type="string" v-model="valiFormData.autoArriveTime" />
				</uni-forms-item>
				<uni-forms-item label="目的地" name="userDestination" required>
					<uni-easyinput v-model="valiFormData.userDestination" placeholder="请输入目的地" />
				</uni-forms-item>
				<uni-forms-item label="用车事宜" name="autoUseReason" required>
					<uni-easyinput type="textarea" v-model="valiFormData.autoUseReason" placeholder="请输入用车事宜" />
				</uni-forms-item>
			</uni-forms>
			<!-- <button type="primary" @click="handleButtonClick">提交</button> -->
			<button type="primary" @click="dialogToggle('info')">提交</button>
		</view>
	</view>
	<view>
		<!-- 提示窗示例 -->
		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog :type="msgType" cancelText="取消" confirmText="确认" title="提醒" content="此操作将提交用车申请,是否继续？"
				@confirm="dialogConfirm" @close="dialogClose"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		name: "autoApply",
		data() {
			return {
				valiFormData: {
					userDepartment: "",
					userName: "",
					userId: "",
					userPhone: "",
					autoType: "",
					passengerNum: "",
					autoStartTime: "",
					autoArriveTime: "",
					autoUseReason: "",
					submitTime: "",
					userDestination: "",
					autoOrderStatus: "流转中",
					autoOrderProgress: "1"
				},
				SubmitTodo: {
					userId: "",
					todoTime: "",
					todoType: "",
					orderId: "",
					todoStatus: ""
				},
				ref: "valiForm",
				DepartmentAdminId: null,
				NextUserRole: "部门管理员",
				AutoOrderId: null,
				SubmitCode: [],
				departmentRange: [{
						value: "销售部",
						text: "销售部"
					},
					{
						value: "财务部",
						text: "财务部"
					},
					{
						value: "市场部",
						text: "市场部"
					}
				],
				autoTypeRange: [{
						value: "商务车",
						text: "商务车"
					},
					{
						value: "客车",
						text: "客车"
					},
					{
						value: "货车",
						text: "货车"
					}
				],
				// 校验规则
				rules: {
					userDepartment: {
						rules: [{
							required: true,
							errorMessage: '用车部门不能为空'
						}]
					},
					userName: {
						rules: [{
							required: true,
							errorMessage: '姓名不能为空'
						}]
					},
					userId: {
						rules: [{
							required: true,
							errorMessage: '工号不能为空'
						}]
					},
					userPhone: {
						rules: [{
							required: true,
							errorMessage: '申请人电话不能为空'
						}]
					},
					autoType: {
						rules: [{
							required: true,
							errorMessage: '车型不能为空'
						}]
					},
					passengerNum: {
						rules: [{
							required: true,
							errorMessage: '成员数不能为空'
						}]
					},
					autoStartTime: {
						rules: [{
							required: true,
							errorMessage: '取车时间不能为空'
						}]
					},
					autoArriveTime: {
						rules: [{
							required: true,
							errorMessage: '截止时间不能为空'
						}]
					},
					userDestination: {
						rules: [{
							required: true,
							errorMessage: '目的地不能为空'
						}]
					},
					autoUseReason: {
						rules: [{
							required: true,
							errorMessage: '用车事宜不能为空'
						}]
					}
				},
			};
		},
		methods: {
			UpdateCurrentTime() {
				const currentDateTime = new Date();

				const year = currentDateTime.getFullYear();
				const month = String(currentDateTime.getMonth() + 1).padStart(2, '0');
				const day = String(currentDateTime.getDate()).padStart(2, '0');

				const hours = String(currentDateTime.getHours()).padStart(2, '0');
				const minutes = String(currentDateTime.getMinutes()).padStart(2, '0');
				const seconds = String(currentDateTime.getSeconds()).padStart(2, '0');

				this.valiFormData.submitTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

				console.log('Updated submit_time:', this.valiFormData.submitTime);
			},
			addAutoOrder() {
				return new Promise((resolve, reject) => {
					this.$refs[this.ref].validate().then(() => {
						console.log('Form submission successful');
						console.log('Submitted data:', this.valiFormData);
						this.UpdateCurrentTime();

						// Send data to the backend
						uni.request({
							url: 'http://localhost:8088/addAutoOrder',
							method: 'POST',
							data: this.valiFormData,
							success: (res) => {
								console.log('Backend response:', res.data);
								uni.showToast({
									title: '提交成功'
								});
								resolve();
							},
							fail: (err) => {
								console.error('Error submitting data:', err);
								uni.showToast({
									title: '提交失败，请稍后重试',
									icon: 'none'
								});
								reject(err);
							},
						});

					}).catch((err) => {
						console.log('Validation errors:', err);
						// Print specific error information for each field
						Object.keys(err).forEach(field => {
							console.log(`Error in ${field}: ${err[field]}`);
						});

						uni.showToast({
							title: '表单校验失败，请检查输入',
							icon: 'none'
						});
						reject(err);
					});
				});
			},
			queryDepartmentUserId() {
				console.log('Executing queryDepartmentUserId');
				return new Promise((resolve, reject) => {
					if (this.NextUserRole === undefined || this.NextUserRole === null) {
						console.error('Invalid value for NextUserRole:', this.NextUserRole);
						reject('Invalid value for NextUserRole');
						return;
					}

					uni.request({
						url: 'http://localhost:8088/queryDepartmentUserId?userRole=' + this.NextUserRole +
							'&userDepartment=' + this.valiFormData.userDepartment,
						method: 'GET',
						success: (res) => {
							console.log('Server response:', res.data);
							const temp = res.data.data;

							if (temp !== null && temp !== undefined) {
								const result = Object.values(temp);

								if (result.length > 0) {
									this.DepartmentAdminId = result[0];
									resolve();
								} else {
									console.error('Empty result array:', result);
									reject('Empty result array');
								}
							} else {
								console.error('Invalid server response:', res.data);
								reject('Invalid server response');
							}
						},
						fail: (err) => {
							console.error(err);
							reject(err);
						}
					});
				});
			},

			GetAutoOrderId() {
				console.log('Executing GetAutoOrderId');
				return new Promise((resolve, reject) => {
					uni.request({
						url: 'http://localhost:8088/getAutoOrderId',
						method: 'GET',
						data: {
							submitTime: this.valiFormData.submitTime
						},
						success: (res) => {
							const temp = res.data.data;
							const result = Object.values(temp);
							this.AutoOrderId = result[0];
							console.log(this.AutoOrderId);
							resolve();
						},
						fail: (err) => {
							console.error(err);
							reject(err);
						},
					});
				});
			},
			AddTodo() {
				return new Promise((resolve, reject) => {
					if (!this.DepartmentAdminId || !this.AutoOrderId) {
						reject('DepartmentAdminId or AutoOrderId is not set.');
						return;
					}
					this.SubmitTodo.userId = this.DepartmentAdminId;
					this.SubmitTodo.todoTime = this.valiFormData.submitTime; // 修正拼写错误
					this.SubmitTodo.todoType = "用车申请部门审批";
					this.SubmitTodo.orderId = this.AutoOrderId;
					this.SubmitTodo.todoStatus = "未完成";
					uni.request({
						url: 'http://localhost:8088/insertTodo',
						method: 'POST',
						data: this.SubmitTodo,
						success: (res) => {
							this.SubmitCode.push(res.data.code);
							if (res.data.code === '0') {
								console.log(res.data.code);
								resolve();
							} else {
								console.log(res.data.msg);
								reject(res.data.msg);
							}
						},
						fail: (err) => {
							console.log(err);
							reject(err);
						},
					});
				});
			},


			handleButtonClick() {
				// Button click event handler
				this.addAutoOrder()
					.then(() => {
						return this.queryDepartmentUserId();
					})
					.then(() => {
						return this.GetAutoOrderId();
					})
					.then(() => {
						return this.AddTodo();
					})
					.catch((error) => {
						console.error('Error:', error);
					});
			},
			dialogToggle(type) {
				this.msgType = type
				this.$refs.alertDialog.open()
			},
			dialogConfirm() {
				console.log('点击确认')
				this.handleButtonClick();
			},
			dialogClose() {
				console.log('点击取消')
			},
		},
	};
</script>

<style lang="scss">
	.example {
		padding: 15px;
		background-color: #fff;
	}

	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		margin-left: 10px;
	}
</style>